package be.pluyckx.batteryprogress.activity.fragment.info.calculators;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import be.pluyckx.batteryprogress.R;
import be.pluyckx.batteryprogress.activity.fragment.info.InfoFragment;
import be.pluyckx.batteryprogress.application.Constants;
import be.pluyckx.batteryprogress.data.history.BatteryHistory;

/**
 * Created by Philip on 21/08/13.
 * <p/>
 * A Fragment which hold the TabHost to switch between different InfoFragments.
 */
public class LevelBatteryFragment extends Fragment {
  private static String KEY_LAST_TAB = "level_battery_last_tab";

  private FragmentTabHost mTabHostCalculators;
  private BatteryHistory mBatteryHistory = BatteryHistory.getHistory();

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_battery_level, container, false);

    mTabHostCalculators = (FragmentTabHost) v.findViewById(R.id.tabhost_level_battery);

    mTabHostCalculators.setup(getActivity(), getActivity().getSupportFragmentManager(), R.id.realtabcontent_battery_level);

    initTabs();

    return v;
  }

  /**
   * Initzialize the tabs.
   */
  private void initTabs() {
    String tabTitle = getResources().getString(R.string.tab_real_time);
    mTabHostCalculators.addTab(mTabHostCalculators.newTabSpec(tabTitle).setIndicator(tabTitle),
        AverageRealTimeInfoFragment.class, null);

    tabTitle = getResources().getString(R.string.tab_average);
    mTabHostCalculators.addTab(mTabHostCalculators.newTabSpec(tabTitle).setIndicator(tabTitle),
        AverageInfoFragment.class, null);
  }

  @Override
  public void onResume() {
    super.onResume();

    mTabHostCalculators.setCurrentTab(getActivity().getSharedPreferences(Constants.PREFERENCES_NAME,
        Context.MODE_PRIVATE).getInt(KEY_LAST_TAB,
        0));
  }

  @Override
  public void onPause() {
    getActivity().getSharedPreferences(Constants.PREFERENCES_NAME, Context.MODE_PRIVATE)
        .edit()
        .putInt(KEY_LAST_TAB, mTabHostCalculators.getCurrentTab())
        .commit();

    super.onPause();
  }

  /**
   * Returns the current tab
   *
   * @return The InfoFragment representing the current tab.
   */
  private InfoFragment getCurrentTab() {
    String tag = mTabHostCalculators.getCurrentTabTag();
    Fragment fragment = getActivity().getSupportFragmentManager().findFragmentByTag(tag);
    try {
      return (InfoFragment) fragment;
    } catch (ClassCastException ex) {
      ex.printStackTrace();
      return null;
    }
  }
}
